﻿using System.Linq.Expressions;
using AutoMapper;
using CozeDomain.Entities;
using CozeDomain.IRepositories;
using CozeDomain.IServices;
using D.Util.UtilCache;
using D.UtilCore.Dtos;
using D.UtilCore.JwtUtil; 
using D.UtilFreesqlOrm;
using Microsoft.AspNetCore.Http;
using D.Util.UtilNLog;
using CozeDto.ProjectDtos;
using CozeDto.UserDtos;

namespace CozeDomain.Services
{
    /// <summary>
    /// 管理员业务实现
    /// </summary>
    public class ProjectService : BaseService<ProjectEntity>, IProjectService
    {
        private readonly IMapper _mapper;
        private readonly ICacheService _cache;
        private readonly IJwtService _tokenService;
        private readonly INLogService _nlogService;
        private readonly IProjectEntityRepository _repository;
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 构造注入
        /// </summary>
        public ProjectService(IMapper mapper, ICacheService cache, IJwtService tokenService, INLogService nlogService, IHttpContextAccessor httpContextAccessor,
            IProjectEntityRepository repository)
        {
            // 用于base方法
            base._baseDal = repository;
            this._repository = repository;
            _cache = cache;
            _mapper = mapper;
            _nlogService = nlogService;
            _tokenService = tokenService;
            _httpContextAccessor = httpContextAccessor;
        }

        #region 增删改查

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> AddProjectAsync(ReqAddProject reqModel)
        {
            var insertEntity = _mapper.Map<ReqAddProject, ProjectEntity>(reqModel);
            insertEntity.Source = "系统";
            insertEntity.Status = false;
            insertEntity.DeleteFlag = false;
            insertEntity.CreateTime = DateTime.Now;
            insertEntity.Id = D.UtilFreesqlOrm.FreesqlOrm.NewId;

            var dbres = await _repository.AddAsync(insertEntity);

            return dbres.NormalResponse();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> DeleteProjectAsync(List<string> ids)
        {
            var dbres = await _repository.DeleteAsync(m => ids.Contains(m.Id));
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> UpdateProjectAsync(ReqUpdateProject reqModel)
        {
            var updateEntity = await _repository.GetModelAsync(m => m.Id == reqModel.Id);
            if (updateEntity == null)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, Msg = "该信息不存在" };
            }

            updateEntity.BotId = reqModel.BotId;
            updateEntity.ProjectType = reqModel.ProjectType;
            updateEntity.Source = reqModel.Source;
            updateEntity.PrivateKey = reqModel.PrivateKey;
            updateEntity.PublickKey = reqModel.PublickKey;
            updateEntity.Status = reqModel.Status;
            updateEntity.Example = reqModel.Example;
            updateEntity.Token = reqModel.Token;
            updateEntity.Instruction = reqModel.Instruction;
            updateEntity.Method = reqModel.Method;
            updateEntity.Name = reqModel.Name;
            updateEntity.Category = reqModel.Category;
            updateEntity.Icon = reqModel.Icon;
            updateEntity.Flag = reqModel.Flag;
            updateEntity.SinglePrice = reqModel.SinglePrice;
            updateEntity.ExperiencePrice = reqModel.ExperiencePrice;
            updateEntity.MonthlyCardPrice = reqModel.MonthlyCardPrice;
            updateEntity.Features = reqModel.Features;
            updateEntity.Description = reqModel.Description;
            updateEntity.UpdateTime = DateTime.Now;
            updateEntity.UpdateUser = reqModel.UpdateUser;

            var dbres = await _repository.UpdateAsync(updateEntity);

            return dbres.NormalResponse();
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<RepProjectInfo>> GetProjectAsync(string id)
        {
            var dbres = await _repository.GetModelAsync(m => m.Id == id);
            var res = _mapper.Map<ProjectEntity, RepProjectInfo>(dbres);
            return res.GetResponse();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<RepProjectInfo>>> QueryProjectListAsync()
        {
            var dbres = await _repository.GetListAsync();
            var res = _mapper.Map<List<ProjectEntity>, List<RepProjectInfo>>(dbres);
            return res.GetResponse();
        }

        /// <summary>
        /// 获取分页
        /// </summary>
        /// <param name="reqQueryProjectPage"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageModel<RepProjectInfo>>> QueryProjectPagesAsync(ReqQueryProjectPage reqQueryProjectPage)
        {
            Expression<Func<ProjectEntity, bool>> where = null;

            if (!string.IsNullOrEmpty(reqQueryProjectPage.Name))
            {
                where = where.And(m => m.Name.Contains(reqQueryProjectPage.Name));
            }

            if (!string.IsNullOrEmpty(reqQueryProjectPage.BotId))
            {
                where = where.And(m => m.BotId.Contains(reqQueryProjectPage.BotId));
            }

            var dbres = await _repository.GetPagesAsync(reqQueryProjectPage.PageSize, reqQueryProjectPage.PageNo, where, m => m.CreateTime);

            var resData = _mapper.Map<List<ProjectEntity>, List<RepProjectInfo>>(dbres.Data);
            PageModel<RepProjectInfo>? res = new PageModel<RepProjectInfo>()
            {
                PageNo = dbres.PageNo,
                PageSize = dbres.PageSize,
                TotalCount = dbres.TotalCount,
                TotalPage = dbres.TotalPage,
                Data = resData
            };

            return res.GetResponse();
        }
        #endregion
    }
}